package singleton.practice_01;

/**
 * @author yi qiang
 * @date 2021/9/12 13:12
 */
public class SingletonType01 {

    public static void main(String[] args) {
        Singleton1.getInstance().test();
        Singleton2.getInstance().test();
    }

}

/**
 * 饿汉式单例模式
 * <br> 1. 构造器必须私有
 * <br> 2. 实例必须为静态
 */
class Singleton1 {

    private Singleton1() {
    }

    private static final Singleton1 SINGLETON = new Singleton1();

    public static Singleton1 getInstance() {
        return SINGLETON;
    }

    public void test() {
        System.out.println("test");
    }
}

/**
 * 饿汉式单例模式: 静态代码块
 * <br> 1. 构造器私有
 * <br> 2. 属性必须为静态
 * <br> 3. 使用静态代码块实例化
 */
class Singleton2 {

    private Singleton2() {}

    private static final Singleton2 SINGLETON;

    static {
        SINGLETON = new Singleton2();
    }

    public static Singleton2 getInstance() {
        return SINGLETON;
    }

    public void test() {
        System.out.println("test");
    }

}

